import Vue from 'vue';
import axios from 'axios';
import urlEnum from './urlEnum'
import store from '@/store'

import { Message, MessageBox } from 'element-ui'

// 请求基地址
let config = {
  baseURL: 'http://127.0.0.1:7991/api/v1/',
  timeout: 5000
};

// 创建
const service = axios.create(config);

// 请求拦截
service.interceptors.request.use(
  config => {
    // 如果配置了携带token才携带
    if (config.isToken) {
      config.headers['token'] = window.sessionStorage.getItem('token')
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
);

// 响应拦截
service.interceptors.response.use(
  response => {
    const res = response.data
    return res
  },
  error => {
    if (error && error.response && error.response.data) {
      // 防止重复出现
      if(document.getElementsByClassName('el-message').length == 0){
        Message({
          message: error.response.data.msg,
          type: 'error',
          duration: 2 * 1000
        })
      }
      if (error.response.data.errorCode === 20003) {
        // 防止重复出现
        if(document.getElementsByClassName('el-message-box').length == 0){
          MessageBox.confirm(
            'Token已过期，请重新登录。',
            '确定登出',
            {
              confirmButtonText: '重新登录',
              cancelButtonText: '取消',
              type: 'warning'
            }
          ).then(() => {
            store.dispatch('user/logout')
          })
        }
      }
    }
    return Promise.reject(error)
  }
);

// 在axios上封装一层可以匹配路由地址的功能
let _axios = {
  // get请求,默认携带token,isToken传false不携带
  get: (url,isToken = true) => {
    return service.get(urlEnum[url],{isToken})
  },
  // post请求,默认携带token,isToken传false不携带
  post: (url,data = {},isToken = true) => {
    return service.post(urlEnum[url],data,{isToken})
  }
}

// 挂载到Vue上
Plugin.install = (Vue) => {
  Vue.axios = _axios;
  window.axios = _axios;
  Object.defineProperties(Vue.prototype, {
    axios: {
      get() {
        return _axios;
      }
    },
    $axios: {
      get() {
        return _axios;
      }
    },
  });
};

Vue.use(Plugin)

export default Plugin;